package prom

import (
	"errors"
	"fmt"
	"github.com/parnurzeal/gorequest"
	"strconv"
	"time"
	"ubi-helper/src/common"
)

const (
	SERVER_URL      = "http://117.50.35.145:9090"
	QUERY_API       = "/api/v1/query"
	QUERY_RANGE_API = "/api/v1/query_range"
)

type PromQueryRequest struct {
	Query string // 查询参数 不能为空
	Time  string // 查询时间 可空 格式：yyyy-MM-dd hh:mm:ss
}

type PromQueryRangeRequest struct {
	Query string // 查询参数
	Start string // 查询时间 不能为空 格式：yyyy-MM-dd hh:mm:ss
	End   string // 查询时间 不能为空 格式：yyyy-MM-dd hh:mm:ss
	Step  string // 查询步长 可空 默认15s 格式：15s 1m
}

//瞬时查询
func (pqr *PromQueryRequest) QueryByProm() (string, error) {
	common.Logger.Info("调用瞬时查询API")
	uri := SERVER_URL + QUERY_API
	if pqr.Query != "" {
		uri = uri + "?query=" + pqr.Query
	} else {
		return "", errors.New("查询参数不能为空")
	}
	time := pqr.Time
	timestamp := localTime2Unix(time)
	if time != "" {
		uri = uri + "&time=" + strconv.FormatInt(timestamp, 10)
	}
	request := gorequest.New()
	_, body, errs := request.Get(uri).End()
	if errs != nil {
		fmt.Println(errs)
		return "", errors.New("查询接口异常")
	}
	return body, nil
}

//区间查询
func (pqr *PromQueryRangeRequest) QueryRangeByProm() (string, error) {
	uri := SERVER_URL + QUERY_RANGE_API
	if pqr.Query != "" {
		uri = uri + "?query=" + pqr.Query
	} else {
		return "", errors.New("查询参数不能为空")
	}
	step := pqr.Step
	if step == "" {
		step = "15s"
	}
	uri = uri + "&step=" + step
	start := pqr.Start
	startTimestamp := localTime2Unix(start)
	if start != "" {
		uri = uri + "&start=" + strconv.FormatInt(startTimestamp, 10)
	}
	end := pqr.End
	endTimestamp := localTime2Unix(end)
	if start != "" {
		uri = uri + "&end=" + strconv.FormatInt(endTimestamp, 10)
	}
	fmt.Println(uri)
	request := gorequest.New()
	_, body, errs := request.Get(uri).End()
	if errs != nil {
		fmt.Println(errs)
		return "", errors.New("查询接口异常")
	}
	return body, nil
}

//时间转换 将北京时间转换为timestamp
func localTime2Unix(timeStr string) int64 {
	var loc, _ = time.LoadLocation("Local")
	p, _ := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
	timestamp := p.Unix()
	return timestamp
}
